package com.sanjiahantang.ythshopping.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.config.SPConfig;
import com.sanjiahantang.ythshopping.fragment.CategoryFragment;
import com.sanjiahantang.ythshopping.fragment.HomeFragment;
import com.sanjiahantang.ythshopping.fragment.MainNearbyFragment;
import com.sanjiahantang.ythshopping.fragment.MeFragment;
import com.sanjiahantang.ythshopping.fragment.ShoppingCartFragment;
import com.sanjiahantang.ythshopping.model.PersonalModel;
import com.sanjiahantang.ythshopping.presenter.PersonalPresenter;
import com.sanjiahantang.ythshopping.utils.SPUtils;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.PersonalView;
import com.sanjiahantang.shopping.uilibrary.drawable.CartDrawable;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 *
 */
public class MainActivity extends AppCompatActivity implements
        OnCheckedChangeListener, PersonalView {
    private static FragmentManager fMgr;
    private RadioButton rbHome;
    private RadioButton rbNearby;
    private RadioButton rbCategory;
    private RadioButton rbShoppingCart;
    private RadioButton rbMe;
    private RadioGroup radioGroup;

    private PushAgent mPushAgent;

    private PersonalPresenter mPresenter;//初始化个人信息

    private String goodsNum = "";
    private boolean isFromWebView = false;
    public static final int RESULT_NEAR = 0x0002;
    public static final int RESULT_MY = 0x0003;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化个人信息
        mPresenter = new PersonalPresenter(this);

        ConfigValue.DATA_KEY = (String) SPUtils.get(this, SPConfig.KEY,"");

        registerBroadcastReceiver();

        SPUtils.put(this, SPConfig.FRAGMENT, 0);
        // 获取FragmentManager实例
        fMgr = getSupportFragmentManager();
        dealBottomButtonsClickEvent();
        initFragment();
        //网络检查
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(this)) {
            Utils.showToast(this,"网络好像阻塞了哦，亲");
        }else
            mPresenter.getPersonalInfo(this);
        //开启推送服务
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        //开启推送并设置注册的回调处理
        mPushAgent.enable(mRegisterCallback);
        getFragmentIndex(getIntent().getIntExtra("index",0));
    }

    private void getFragmentIndex(int i) {
        if(i!=0){
            isFromWebView = true;
        }
        setFragmentIndex(i);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        if (fMgr == null){
            int flag = (int) SPUtils.get(this,SPConfig.FRAGMENT,0);
            // 获取FragmentManager实例
            fMgr = getSupportFragmentManager();
            dealBottomButtonsClickEvent();
            startFragment(flag);
        }
        super.onResume();
        System.gc();
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setFragmentIndex(int index){
        Log.e("setFragmentIndex",String.valueOf(index));
        switch (index){
            case 0:
//                onCheckedChanged(radioGroup, R.id.rbHome);
                rbHome.setChecked(true);
//                rbHome.setSelected(true);
                radioGroup.check(R.id.rbHome);
                break;
            case 1:
//                onCheckedChanged(radioGroup, R.id.rbCategory);
//                rbCategory.setSelected(true);
                rbCategory.setChecked(true);
                radioGroup.check(R.id.rbCategory);
                break;
            case 2:
//                onCheckedChanged(radioGroup, R.id.rbnearby);
//                rbNearby.setSelected(true);
                rbNearby.setChecked(true);
                radioGroup.check(R.id.rbnearby);
                break;
            case 3:
//                onCheckedChanged(radioGroup, R.id.rbShoppingCart);
//                rbShoppingCart.setSelected(true);
                rbShoppingCart.setChecked(true);
                radioGroup.check(R.id.rbShoppingCart);
                break;
            case 4:
//                onCheckedChanged(radioGroup, R.id.rbMe);
//                rbMe.setSelected(true);
                rbMe.setChecked(true);
                radioGroup.check(R.id.rbMe);
                break;
        }

    }

    private void startFragment(int i){
        FragmentTransaction ft = fMgr.beginTransaction();
        switch (i){
            case 0:
                HomeFragment taskFragment = new HomeFragment();
                ft.replace(R.id.fragmentRoot, taskFragment, "homeFragment");
                ft.addToBackStack("homeFragment");
                ft.commit();
                break;
            case 1:
                CategoryFragment categoryFragment = new CategoryFragment();
                ft.replace(R.id.fragmentRoot, categoryFragment,
                        "categoryFragment");
                ft.addToBackStack("categoryFragment");
                ft.commit();
                break;
            case 2:
                MainNearbyFragment nearbyFragment = new MainNearbyFragment();
                ft.replace(R.id.fragmentRoot, nearbyFragment,
                        "MainNearbyFragment");
                ft.addToBackStack("MainNearbyFragment");
                ft.commit();
                break;
            case 3:
                ShoppingCartFragment shoppingCartFragment = new ShoppingCartFragment();
                ft.replace(R.id.fragmentRoot, shoppingCartFragment,
                        "shoppingCartFragment");
                ft.addToBackStack("shoppingCartFragment");
                ft.commit();
                break;
            case 4:
                MeFragment meFragment = new MeFragment();
                ft.replace(R.id.fragmentRoot, meFragment, "meFragment");
                ft.addToBackStack("meFragment");
                ft.commit();
                break;
        }
    }

    /**
     * 初始化首个Fragment
     */
    private void initFragment() {
        FragmentTransaction ft = fMgr.beginTransaction();
        HomeFragment homeFragment=new HomeFragment();
        ft.add(R.id.fragmentRoot, homeFragment, "homeFragment");
        ft.addToBackStack("homeFragment");
        ft.commit();

    }

    /**
     * 处理底部点击事件
     */
    private void dealBottomButtonsClickEvent() {

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        rbHome = (RadioButton) findViewById(R.id.rbHome);
        rbNearby = (RadioButton) findViewById(R.id.rbnearby);
        rbCategory = (RadioButton) findViewById(R.id.rbCategory);
        rbShoppingCart = (RadioButton) findViewById(R.id.rbShoppingCart);
        rbMe = (RadioButton) findViewById(R.id.rbMe);
        radioGroup.setOnCheckedChangeListener(this);
    }

    // 点击返回按钮
    @Override
    public void onBackPressed() {
        if (fMgr.findFragmentByTag("homeFragment") != null
                && !fMgr.findFragmentByTag("homeFragment").isResumed() && !isFromWebView) {
            rbHome.toggle();
            SPUtils.put(this, SPConfig.FRAGMENT, 0);
        } else {
            // super.onBackPressed();
//            AppManager.getAppManager().finishAllActivity();
            this.finish();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        System.gc();
        FragmentTransaction ft;
        switch (checkedId) {
            case R.id.rbHome:
                SPUtils.put(this, SPConfig.FRAGMENT, 0);
                ConfigValue.iconFlag = 0;
                CartDrawable cartDrawableH = new CartDrawable(this,ConfigValue.iconFlag);
                cartDrawableH.setCatNum(goodsNum);
                rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawableH, null, null);
                ft = fMgr.beginTransaction();
                if (fMgr.findFragmentByTag("homeFragment") != null) {
                    ft.replace(R.id.fragmentRoot,
                            fMgr.findFragmentByTag("homeFragment"), "homeFragment");
                    ft.commitAllowingStateLoss();
                } else {
                    HomeFragment taskFragment=new HomeFragment();
                    ft.replace(R.id.fragmentRoot, taskFragment, "homeFragment");
                    ft.addToBackStack("homeFragment");
                    ft.commit();
                }
                break;

            case R.id.rbnearby:
                SPUtils.put(this, SPConfig.FRAGMENT, 2);
                ConfigValue.iconFlag = 0;
                CartDrawable cartDrawableN = new CartDrawable(this,ConfigValue.iconFlag);
                cartDrawableN.setCatNum(goodsNum);
                rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawableN, null, null);

                ft = fMgr.beginTransaction();
                if (fMgr.findFragmentByTag("MainNearbyFragment") != null) {
                    ft.replace(R.id.fragmentRoot,
                            fMgr.findFragmentByTag("MainNearbyFragment"), "MainNearbyFragment");
                    ft.commitAllowingStateLoss();
                } else {
                    MainNearbyFragment mainnearby=new MainNearbyFragment();
                    ft.replace(R.id.fragmentRoot, mainnearby, "MainNearbyFragment");
                    ft.addToBackStack("MainNearbyFragment");
                    ft.commit();
                }
                break;
            case R.id.rbCategory:
                SPUtils.put(this, SPConfig.FRAGMENT, 1);
                ConfigValue.iconFlag = 0;
                CartDrawable cartDrawableC = new CartDrawable(this,ConfigValue.iconFlag);
                cartDrawableC.setCatNum(goodsNum);
                rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawableC, null, null);
                ft = fMgr.beginTransaction();
                if (fMgr.findFragmentByTag("categoryFragment") != null) {
                    ft.replace(R.id.fragmentRoot,
                            fMgr.findFragmentByTag("categoryFragment"),
                            "categoryFragment");
                    ft.commitAllowingStateLoss();
                } else {
                    CategoryFragment categoryFragment = new CategoryFragment();
                    ft.replace(R.id.fragmentRoot, categoryFragment,
                            "categoryFragment");
                    ft.addToBackStack("categoryFragment");
                    ft.commit();
                }
                break;
            case R.id.rbShoppingCart:
                SPUtils.put(this, SPConfig.FRAGMENT, 3);
                ConfigValue.iconFlag = 1;
                CartDrawable cartDrawable = new CartDrawable(this,ConfigValue.iconFlag);
                cartDrawable.setCatNum(goodsNum);
                rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawable, null, null);
                ft = fMgr.beginTransaction();
                if (fMgr.findFragmentByTag("shoppingCartFragment") != null) {
                    ft.replace(R.id.fragmentRoot,
                            fMgr.findFragmentByTag("shoppingCartFragment"),
                            "shoppingCartFragment");
                    ft.commitAllowingStateLoss();
                } else {
                    ShoppingCartFragment shoppingCartFragment = new ShoppingCartFragment();
                    ft.replace(R.id.fragmentRoot, shoppingCartFragment,
                            "shoppingCartFragment");
                    ft.addToBackStack("shoppingCartFragment");
                    ft.commit();
                }
                break;
            case R.id.rbMe:
                SPUtils.put(this,SPConfig.FRAGMENT,4);
                ConfigValue.iconFlag = 0;
                CartDrawable cartDrawableM = new CartDrawable(this,ConfigValue.iconFlag);
                cartDrawableM.setCatNum(goodsNum);
                rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawableM, null, null);
                ft = fMgr.beginTransaction();
                if (fMgr.findFragmentByTag("meFragment") != null) {
                    ft.replace(R.id.fragmentRoot,
                            fMgr.findFragmentByTag("meFragment"), "meFragment");
                    ft.commitAllowingStateLoss();
                    ((MeFragment)fMgr.findFragmentByTag("meFragment")).setLmIndex(4);
                } else {
                    MeFragment meFragment = new MeFragment();
                    ft.replace(R.id.fragmentRoot, meFragment, "meFragment");
                    ft.addToBackStack("meFragment");
                    ft.commit();
                }
                break;
            default:
                break;
        }

    }

    public Handler handler = new Handler();
    //此处是注册的回调处理
    //参考集成文档的1.7.10
    //http://dev.umeng.com/push/android/integration#1_7_10
    public IUmengRegisterCallback mRegisterCallback = new IUmengRegisterCallback() {

        @Override
        public void onRegistered(String registrationId) {
            // TODO Auto-generated method stub
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if (mPushAgent.isRegistered()) {
                        //成功
                    }
                }
            });
        }
    };

    //获取个人信息
    @Override
    public void onPersonalInfo(PersonalModel response) {
        if (response.getCode().equals("1"))
            this.setCartGoodsNums(response.getData().getNumber());
    }

    //修改购物车角标回调
    @Override
    public void setCartGoodsNums(String nums) {
        goodsNum = nums;
        CartDrawable cartDrawable = new CartDrawable(this,ConfigValue.iconFlag);
        cartDrawable.setCatNum(nums);
        rbShoppingCart.setCompoundDrawablesWithIntrinsicBounds(null, cartDrawable, null, null);
    }

    //角标增加，用于在商品详情页增加商品至购物车时调用

    @Override
    public void addCartGoodsNums(int nums) {
        int now = Integer.parseInt(goodsNum) + nums;
        goodsNum = String.valueOf(now);
        CartDrawable cartDrawable = (CartDrawable) rbShoppingCart.getCompoundDrawables()[1];
        cartDrawable.addNums(nums);
        cartDrawable.start();
    }

    //注册广播接收商品详情页修改购物车数量之后发送的广播

    private BroadcastReceiver mBroadcastReseiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS)) {
                int addNum = intent.getIntExtra("addGoodsNums", 0);
                String total = intent.getStringExtra("cartgoodsnum");
                int homeFlag = intent.getIntExtra("home",0);
                if (addNum != 0)
                    addCartGoodsNums(addNum);
                if (null != total && !total.equals(""))
                    setCartGoodsNums(total);
                if(homeFlag != 0)
                    if (fMgr.findFragmentByTag("homeFragment") != null
                            && !fMgr.findFragmentByTag("homeFragment").isResumed()) {
                        rbHome.toggle();
                    }
            }
        }
    };

    public void registerBroadcastReceiver() {
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS);
        //注册广播
        registerReceiver(mBroadcastReseiver, mIntentFilter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESULT_NEAR && resultCode == RESULT_OK){
            setFragmentIndex(data.getIntExtra("index",0));
        }else if (requestCode == RESULT_MY  && resultCode == RESULT_OK)
        {
            if(fMgr != null && fMgr.findFragmentByTag("meFragment") != null){
                ((MeFragment)fMgr.findFragmentByTag("meFragment")).setLmIndex(data.getIntExtra("index",0));
            }
        }
    }
}
